<template>
  <div style="padding: 20px;">
    <el-button @click="atchDownload" type="primary">下载</el-button>
  </div>
</template>

<script>
// 批量下载图片并打包到zip压缩包中
// 参考：https://blog.csdn.net/guizi0809/article/details/119421502
// https://www.yisu.com/zixun/316800.html
// https://blog.csdn.net/weixin_42484657/article/details/122321802
// https://blog.csdn.net/weixin_62452941/article/details/123707168
import JSZip from "jszip";
import FileSaver from "file-saver";
export default {
  data() {
    return {
      images: [
        { url: 'http://imgs.itchenliang.club/img/202208161645800.png', id: '01.png' },
        { url: 'http://imgs.itchenliang.club/img/202208161642845.png', id: '02.png' },
        { url: 'http://imgs.itchenliang.club/img/202208161640518.png', id: '03.png' },
        { url: 'http://imgs.itchenliang.club/img/202208161638553.png', id: '04.png' },
        { url: 'http://imgs.itchenliang.club/img/202208161635074.png', id: '05.png' }
      ]
    }
  },
  methods: {
    getImgArrayBuffer(url) {
      return new Promise((resolve, reject) => {
        //通过请求获取文件blob格式
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, true);
        xmlhttp.responseType = "blob";
        xmlhttp.onload = function () {
          if (this.status == 200) {
            resolve(this.response);
          } else {
            reject(this.status);
          }
        };
        xmlhttp.send();
      });
    },
    //批量下载
    atchDownload() {
      // this.images 是要下载的图片数组  [{url: 图片地址, id: 图片名称}]
      // 定时器 loading
      this.loading = true;
      this.setTimeout = setTimeout(() => {
        this.loading = false;
      }, 2000);
      let _this = this;
      let zip = new JSZip();
      let cache = {};
      let promises = [];
      for (let item of this.images) {
        const promise = _this.getImgArrayBuffer(item.url).then((data) => {
          // 下载文件, 并存成ArrayBuffer对象(blob)
          zip.file(item.id + ".png", data, { binary: true }); // 逐个添加文件
          cache[item.id] = data;
        });
        promises.push(promise);
      }

      Promise.all(promises)
        .then(() => {
          zip.generateAsync({ type: "blob" }).then((content) => {
            _this.$message("正在压缩，请稍后！");
            // 生成二进制流
            FileSaver.saveAs(content, "打包图片"); // 利用file-saver保存文件  自定义文件名
            _this.$message("压缩完成！");
          });
        })
        .catch((res) => {
          console.log("111111111111");
        });
    },
  },
};
</script>

<style>
</style>